package com.mewpipe.servlet;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.mewpipe.crypt.BCrypt;
import com.mewpipe.dao.DaoFactory;
import com.mewpipe.dao.UserDao;
import com.mewpipe.entity.User;
import com.mewpipe.entity.UserSession;



@SuppressWarnings("serial")
@WebServlet ("/addUser")
public class AddUserServlet extends HttpServlet{
	private UserDao userDao;
	@Override
	public void init() throws ServletException {
		userDao = DaoFactory.getInstance().getUserDao();
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		
		String pseudo = req.getParameter("pseudo");
		String adresse = req.getParameter("adresse");
		String password = BCrypt.hashpw( req.getParameter("password"), BCrypt.gensalt());
		
		String nom =req.getParameter("nom");
		String prenom = req.getParameter("prenom");
		String bday = req.getParameter("bday");
				
		User usertmp = new User();
		usertmp.setPseudo(pseudo);
		usertmp.setAdresse(adresse);
		usertmp.setPassword(password);
		usertmp.setPrenom(prenom);
		usertmp.setNom(nom);
		
		

		if(bday!=null){
		Date dateAnniversaire = null;
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-mm-dd");
		try {
			dateAnniversaire = formatter.parse(bday);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		usertmp.setAge(dateAnniversaire);
		}
		userDao.addUser(usertmp);
		
		UserSession usersession = new UserSession(usertmp.getId(), usertmp.getPseudo(), usertmp.getTypeAcc());
		HttpSession session = req.getSession();
		session.setAttribute("UserSession", usersession);
		
		
		//req.getRequestDispatcher("/Index").forward(req, resp);
		
		
		resp.sendRedirect(req.getServletContext().getContextPath()+"/Index");
	}
}
